from Data import search_file
import os
import shutil
import fitz  # PyMuPDF


# 主函数，pdf合并
def diagnosis_or_maintenance_other_pdf(selected_function, is_chinese, filepaths):
    scg_cref_path = None
    # filepaths = search_file.select_folder()
    if filepaths == "-1":
        return "-1"
    else:
        if selected_function == "分册合稿":
            first_level = filepaths[0].rsplit("\\")[-3]
            second_level = filepaths[0].rsplit("\\")[-2]
            if "维护命令" in first_level:
                scg_cref_path = f'{filepaths[0].rsplit("维护命令", 1)[0]}维护命令\\00-pdf'
            if "诊断命令" in first_level:
                scg_cref_path = f'{filepaths[0].rsplit("诊断命令", 1)[0]}诊断命令\\00-pdf'
            if is_chinese:
                merge_pdf_volumes(filepaths, scg_cref_path, second_level, is_chinese, first_level)
            else:
                merge_pdf_volumes(filepaths, scg_cref_path, second_level, is_chinese, first_level)
            print("程序执行完成!!!")
        # if selected_function == "其它稿件":
        #     scg_cref_path = filepaths[0].rsplit("\\", 1)[0]
        #     merge_other_pdf_volumes(filepaths, scg_cref_path)
        #     print("程序执行完成!!!")


# def merge_other_pdf_volumes(filepaths, scg_cref_path):
#     print("正在完成合稿：")
#     try:
#         # 对文件路径进行排序
#         sorted_files = []
#         # 先找封面文件
#         for file in filepaths:
#             if "封面" in file and "合稿" not in file:
#                 sorted_files.append(file)
#                 break
#
#         # 按数字顺序排序其他文件，跳过包含合稿的文件
#         remaining_files = [f for f in filepaths if "封面" not in f and "合稿" not in f]
#         remaining_files.sort(key=lambda x: int(''.join(filter(str.isdigit, os.path.basename(x).split()[0]))))
#         sorted_files.extend(remaining_files)
#
#         # 开始合并PDF
#         merged_pdf = fitz.open()
#         page_offset = 0
#         all_bookmarks = []
#
#         for file in sorted_files:
#             try:
#                 with fitz.open(file) as pdf:
#                     if pdf.page_count == 0:
#                         continue
#
#                     # 获取文件名作为书签
#                     file_name = os.path.basename(file).replace('.pdf', '')
#                     first_bookmark = [1, file_name, page_offset + 1]
#                     all_bookmarks.append(first_bookmark)
#
#                     # 复制文档
#                     merged_pdf.insert_pdf(pdf)
#
#                     # 获取并处理原始书签
#                     original_toc = pdf.get_toc(simple=False)
#                     if original_toc:
#                         for bookmark in original_toc:
#                             level, title, page, dest = bookmark[:4]
#                             if dest:
#                                 dest_page = dest.get('page', page - 1)
#                                 dest_top = dest.get('to', fitz.Point(0, 0)).y
#                                 adjusted_bookmark = [
#                                     level + 1,
#                                     title,
#                                     dest_page + page_offset + 1,
#                                     {
#                                         "kind": 1,
#                                         "page": dest_page + page_offset,
#                                         "to": fitz.Point(0, dest_top),
#                                         "zoom": 0
#                                     }
#                                 ]
#                                 all_bookmarks.append(adjusted_bookmark)
#
#                     page_offset += pdf.page_count
#
#             except Exception as e:
#                 print(f"\033[31m处理文件 {file} 时出错: {str(e)}\033[0m")
#                 continue
#
#         # 设置书签
#         if len(merged_pdf) > 0 and all_bookmarks:
#             try:
#                 merged_pdf.set_toc(all_bookmarks)
#                 print(f"成功设置 {len(all_bookmarks)} 个书签")
#             except Exception as e:
#                 print(f"\033[31m设置书签时出错: {str(e)}\033[0m")
#
#         # 保存合并后的PDF
#         output_path = os.path.join(scg_cref_path, "已完成合稿.pdf")
#         if os.path.exists(output_path):
#             os.remove(output_path)
#         merged_pdf.save(output_path, garbage=4, clean=True, deflate=True)
#         merged_pdf.close()
#         print(f"已合并PDF文件: {output_path}")
#
#     except Exception as e:
#         print(f"\033[31m合并PDF文件失败: {str(e)}\033[0m")


# 分册pdf合并
def merge_pdf_volumes(files, scg_cref_path, second_level, is_chinese, first_level):
    output_path = None
    try:
        merged_pdf = fitz.open()
        page_offset = 0
        all_bookmarks = []

        for file in files:
            try:
                with fitz.open(file) as pdf:
                    if pdf.page_count == 0:
                        continue

                    # 获取文件名作为一级书签
                    file_name = os.path.basename(file).replace('.pdf', '')
                    first_bookmark = [1, file_name, page_offset + 1]
                    all_bookmarks.append(first_bookmark)

                    # 复制文档
                    merged_pdf.insert_pdf(pdf)

                    # 获取原始书签并处理
                    original_toc = pdf.get_toc(simple=False)  # 获取完整书签信息
                    if original_toc:
                        for bookmark in original_toc:
                            level, title, page, dest = bookmark[:4]
                            if dest:
                                # 提取目标页面和位置信息
                                dest_page = dest.get('page', page - 1)
                                dest_top = dest.get('to', fitz.Point(0, 0)).y
                                # 创建新的书签项，包含精确位置信息
                                adjusted_bookmark = [
                                    level + 1,  # 增加层级，因为文件名是一级
                                    title,
                                    dest_page + page_offset + 1,
                                    {
                                        "kind": 1,
                                        "page": dest_page + page_offset,
                                        "to": fitz.Point(0, dest_top),
                                        "zoom": 0
                                    }
                                ]
                                all_bookmarks.append(adjusted_bookmark)

                    page_offset += pdf.page_count

            except Exception as e:
                print(f"\033[31m处理文件 {file} 时出错: {str(e)}\033[0m")
                continue

        # 检查并设置书签
        if len(merged_pdf) > 0 and all_bookmarks:
            try:
                merged_pdf.set_toc(all_bookmarks)
                print(f"成功设置 {len(all_bookmarks)} 个书签")
            except Exception as e:
                print(f"\033[31m设置书签时出错: {str(e)}\033[0m")

        # 保存合并后的PDF
        if second_level is None:
            output_path = os.path.join(scg_cref_path, "已完成合稿.pdf")
        else:
            # if is_chinese:
            #     output_path = os.path.join(scg_cref_path, f"{second_level}.pdf")
            # else:
            #     # 判断是否包含中文
            #     if any('\u4e00' <= char <= '\u9fff' for char in second_level):
            #         name = volume_name(second_level, True, first_level)
            #         output_path = os.path.join(scg_cref_path, f"{name}.pdf")
            #     else:
            #         name = volume_name(second_level, False, first_level)
            #         output_path = os.path.join(scg_cref_path, f"{name}.pdf")
            output_path = os.path.join(scg_cref_path, f"{second_level}.pdf")
        if os.path.exists(output_path):
            os.remove(output_path)
        merged_pdf.save(output_path, garbage=4, clean=True, deflate=True)
        merged_pdf.close()
        print(f"已合并PDF文件: {output_path}")

    except Exception as e:
        print(f"\033[31m合并PDF文件失败: {str(e)}\033[0m")


# def volume_name(second_level, flag, first_level):
#     num = second_level.split('-')[0]
#     file_name_metadata = [['基础配置', f'{num}-Basic Configuration'],
#                           ['设备管理', f'{num}-Alarm Management'],
#                           ['接口', f'{num}-Interface'],
#                           ['虚拟化', f'{num}-Virtualization'],
#                           ['以太网交换', f'{num}-Ethernet Switching'],
#                           ['IP业务', f'{num}-IP Service'],
#                           ['IP路由', f'{num}-IP Routing'],
#                           ['组播', f'{num}-Multicast'],
#                           ['MPLS', f'{num}-MPLS'],
#                           ['ACL和QoS', f'{num}-ACL and QoS'],
#                           ['安全', f'{num}-Security'],
#                           ['可靠性', f'{num}-Reliability'],
#                           ['网管与监控', f'{num}-Network Control and Monitoring'],
#                           ['无损网络', f'{num}-Lossless Network'],
#                           ['VPN', f'{num}-VPN'],
#                           ['数据中心', f'{num}-Data Center'],
#                           ]
#     if flag:
#         for filename in file_name_metadata:
#             if filename[0] in second_level:
#                 return filename[1]
#     else:
#         if "配置指南" in first_level:
#             if "Basic Configuration" in second_level:
#                 return f"{num}-Basic Configuration"
#             else:
#                 return second_level.split(" Configuration")[0]
#         if "命令参考" in first_level:
#             if "Basic Commands" in second_level:
#                 return f"{num}-Basic Configuration"
#             else:
#                 return second_level.split(" Commands")[0]


if __name__ == '__main__':
    diagnosis_or_maintenance_other_pdf("分册合稿", False)
